//
//  LGPatientWeightChart.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/3/6.
//  呼吸训练统计图

#import "LGPatientBreathRecordChart.h"
#import "LGScrollView.h"
#define topMargin     viewPix(125)

#define leftMargin    viewPix(35)+iPadMargin(10)

#define lineHeight    viewPix(35)

#define scrollWidth   (Screen_W - viewPix(80))

#define scrollHeight  (lineHeight*5+viewPix(20))

@interface LGPatientBreathRecordChart()<UIScrollViewDelegate>
/**   */
@property (nonatomic , strong)UIImageView *iconView;
/**   */
@property (nonatomic , strong)UILabel *unitLabel;
/**   */
@property (nonatomic , strong)LGScrollView *scrollView;
/**   */
@property (nonatomic , strong)UILabel *emptyLabel;
/**   */
@property (nonatomic , strong)NSMutableArray *itemArray;
/**  X轴label */
@property (nonatomic , strong)NSMutableArray *x_AxisArray;
/**  Y轴label */
@property (nonatomic , strong)NSArray *y_AxisArray;

/**   */
@property (nonatomic , strong)NSArray *dayArray;

//呼吸次数、训练时长、压力、振幅、呼气时间
@property (nonatomic , strong)NSArray *dataArray1;
@property (nonatomic , strong)NSArray *dataArray2;
@property (nonatomic , strong)NSArray *dataArray3;
@property (nonatomic , strong)NSArray *dataArray4;
@property (nonatomic , strong)NSArray *dataArray5;
/**   */
@property (nonatomic , strong)NSMutableArray *btnArray;
/**   */
@property (nonatomic , strong)NSMutableArray *lineArray;
/**   */
@property (nonatomic , assign)NSInteger totalCount;
/**   */
@property (nonatomic , assign)CGFloat itemWidth;
/**   */
@property (nonatomic , assign)NSInteger itemIndex;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**   */
@property (nonatomic , copy)NSString *currentTitle;
/**   */
@property (nonatomic , copy)NSString *type;

@end

@implementation LGPatientBreathRecordChart

-(instancetype)initWithType:(NSString *)type frame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.type = type;
        self.itemWidth = scrollWidth/7.0;
        [self createSubView];
        [self createItemView:type];
        [self addSubview:self.alertView];
    }
    return self;
}


-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    self.alertView.hidden = YES;
    if ([dataDic isKindOfClass:[NSDictionary class]] && dataDic.allKeys.count>0) {
        self.totalCount = [dataDic[@"xAxis"] count]>0?[dataDic[@"xAxis"] count]:1;
        NSInteger count = (self.totalCount>7)?7:self.totalCount;
        self.itemWidth = scrollWidth/count;
        self.scrollView.contentSize = CGSizeMake(viewPix(20)+self.itemWidth*self.totalCount, scrollHeight);
        [self.scrollView setContentOffset:CGPointMake(viewPix(20)+self.itemWidth*self.totalCount-scrollWidth-viewPix(10), 0)];
        self.dayArray = dataDic[@"xAxis"];
        //选中
        UIButton *button = self.itemArray[self.itemIndex];
        if (button.selected == NO) {
            [self itemButtonTouched:self.itemArray[self.itemIndex]];
        }else{
            [self setItemIndex:self.itemIndex];
        }
    }
}

//切换类型
-(void)itemButtonTouched:(UIButton *)sender{
    self.alertView.hidden = YES;
    self.currentTitle = [sender titleForState:UIControlStateNormal];
    if (sender.selected == YES) return;
    for (UIButton *button in self.itemArray) {
        button.selected = NO;
    }
    sender.selected = YES;
    self.itemIndex = sender.tag - 1000;
}

-(void)setItemIndex:(NSInteger)itemIndex{
    _itemIndex = itemIndex;
    if (itemIndex == 0) {
        //呼吸次数
        self.unitLabel.text = @"次";
        [self createChartLine:self.dataDic[@"groupTimesAxis"]];
        
    }else if (itemIndex == 1){
        //训练时长
        self.unitLabel.text = @"秒";
        [self createChartLine:self.dataDic[@"trainLengthAxis"]];
        
    }else if (itemIndex == 2){
        //压力
        self.unitLabel.text = @"cmH₂O";
        [self createChartLine:self.dataDic[@"pressuresAxis"]];
        
    }else if (itemIndex == 3){
        //振幅 - 功率
        [self createChartLine:self.dataDic[@"amplitudeAxis"]];
        if ([self.type isEqualToString:@"breath"]) {
            //吸气--功率
            self.unitLabel.text = @"W";
            [self createChartLine:self.dataDic[@"powerAxis"]];
            
        }else{
            //排痰 -- 振幅
            self.unitLabel.text = @"cmH₂O";
            [self createChartLine:self.dataDic[@"amplitudeAxis"]];
        }
        
    }else if (itemIndex == 4){
        //呼气时间 - 能量
        if ([self.type isEqualToString:@"breath"]) {
            //吸气 -- 能量
            self.unitLabel.text = @"J";
            [self createChartLine:self.dataDic[@"energyAxis"]];
            
        }else{
            //排痰 -- 呼气时间
            self.unitLabel.text = @"秒";
            [self createChartLine:self.dataDic[@"timesAxis"]];
        }
    }
}

//创建X轴坐标
-(void)setDayArray:(NSArray *)dayArray{
    _dayArray = dayArray;
    for (UILabel *label in self.x_AxisArray) {
        [label removeFromSuperview];
    }
    [self.x_AxisArray removeAllObjects];
    for (NSInteger i=0; i<dayArray.count; i++) {
//        NSArray *tempArray = [LGNSString(dayArray[i]) componentsSeparatedByString:@"-"];
//        NSString *dayString = [NSString stringWithFormat:@"%@/%@",tempArray[tempArray.count-2],tempArray[tempArray.count-1]];
        UILabel *dayLabel = [UILabel lableWithText:LGNSString(dayArray[i]) colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        dayLabel.frame = CGRectMake(viewPix(10)+self.itemWidth*i, lineHeight*4.5, self.itemWidth, lineHeight);
        dayLabel.tag = 1000+i;
        [self.scrollView addSubview:dayLabel];
        [self.x_AxisArray addObject:dayLabel];
    }
}

-(void)createChartLine:(NSArray *)dataArray{
    self.dataArray = dataArray;
    self.emptyLabel.hidden = (dataArray.count>0)?YES:NO;
    for (UIButton *button in self.btnArray) {
        [button removeFromSuperview];
    }
    [self.btnArray removeAllObjects];
    
    for (CAShapeLayer *layer in self.lineArray) {
        [layer removeFromSuperlayer];
    }
    [self.lineArray removeAllObjects];
    
    //设置Y轴的值
    NSInteger maxValue = 4;
    for (NSInteger i=0; i<dataArray.count; i++) {
        NSInteger value = ceil([dataArray[i] floatValue]);
        maxValue = MAX(maxValue, value);
    }
    maxValue = (maxValue%4==0) ? maxValue : (maxValue/4 + 1)*4;
    CGFloat segment = maxValue/4.0;
    for (NSInteger i=0; i<5; i++) {
        UILabel *label = self.y_AxisArray[i];
        label.text = [NSString stringWithFormat:@"%.0f",maxValue-segment*i];
    }
    
    //创建点和曲线
    NSMutableArray *pointArray = [NSMutableArray array];
    for (NSInteger i=0; i<dataArray.count; i++) {
        CGFloat pointY = scrollHeight-([dataArray[i] floatValue]/segment*lineHeight+viewPix(20)+lineHeight*0.5);
        UIButton *button = [UIButton buttonWithImage:@"体重-Normal" selectImage:@"体重-Select"];
        button.bounds = CGRectMake(0, 0, viewPix(20), viewPix(20));
        button.center = CGPointMake(viewPix(10)+self.itemWidth/2.0+self.itemWidth*i, pointY);
        button.tag = 2000+i;
        [button addTarget:self action:@selector(pointButtonTouch:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:button];
        [self.btnArray addObject:button];
        NSValue *point = [NSValue valueWithCGPoint:button.center];
        [pointArray addObject:point];
    }
    [self drawCurveLine:pointArray lineColor:@"#429BFF"];
}

-(void)pointButtonTouch:(UIButton *)sender{
    NSInteger index = sender.tag-2000;
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *button = [self viewWithTag:2000+i];
        button.selected = (index == i)?YES:NO;
    }

    CGPoint point = [self.scrollView convertPoint:sender.center toView:self];
    CGFloat marginX = (point.x>(Screen_W-viewPix(32))/2.0)?(point.x-viewPix(140)-5):(point.x+5);
    self.alertView.frame = CGRectMake(marginX, point.y+3, viewPix(140), viewPix(35)+viewPix(24));
    self.alertView.dateString = LGNSString(self.dayArray[index]);
    self.alertView.dataArray = @[@{@"icon":@"",@"title":self.currentTitle,@"score":LGNSString(self.dataArray[index]) ,@"status":@""}];
    self.alertView.hidden = NO;
}


//画线
-(void)drawCurveLine:(NSArray *)arry lineColor:(NSString *)color{
    if(arry.count == 0) return;
    CGPoint startPoint = [[arry objectAtIndex:0] CGPointValue];
    CGPoint lastPoint;
    UIBezierPath *lineBeizer = [UIBezierPath bezierPath];
    [lineBeizer setLineWidth:2.0];
    [lineBeizer moveToPoint:startPoint];

    for (NSInteger i = 0;i < arry.count;i++ ) {
        if (i <arry.count-1 ) {
            CGPoint nowPoint = [[arry objectAtIndex:i] CGPointValue];
            CGPoint futPoint  = [[arry objectAtIndex:i+1] CGPointValue];
            [lineBeizer addCurveToPoint:futPoint controlPoint1:CGPointMake((nowPoint.x+futPoint.x)/2, nowPoint.y) controlPoint2:CGPointMake((nowPoint.x+futPoint.x)/2, futPoint.y)];
            if (i == arry.count-2) {
                [lineBeizer moveToPoint:futPoint];//添加连线
                lastPoint = futPoint;
            }
        }
    }
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = lineBeizer.CGPath;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = [UIColor colorWithString:color].CGColor;
    shapeLayer.lineWidth = 2.0;
    [self.scrollView.layer addSublayer:shapeLayer];
    [self.lineArray addObject:shapeLayer];
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *button = [self viewWithTag:2000+i];
        [self.scrollView bringSubviewToFront:button];
        
        UIButton *button2 = [self viewWithTag:3000+i];
        [self.scrollView bringSubviewToFront:button2];
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.alertView.hidden = YES;
    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
        [self.delegate chartViewTouchesBegan];
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    self.alertView.hidden = YES;
    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
        [self.delegate chartViewTouchesBegan];
    }
}


-(void)createSubView{
    self.cornerRidus = 10;
    self.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.iconView];
    [self addSubview:self.titleLabel];
    [self addSubview:self.scrollView];
    [self addSubview:self.unitLabel];
    
    NSArray *titleArray = @[@"160",@"120",@"80",@"40",@"0"];
    NSMutableArray *labelArray = [NSMutableArray array];
    for (NSInteger i=0; i<titleArray.count; i++) {
        //Y轴标题
        UILabel *label = [UILabel lableWithText:titleArray[i] colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        label.frame = CGRectMake(0, topMargin+lineHeight*i, leftMargin, lineHeight);
        [self addSubview:label];
        [labelArray addObject:label];
        //虚线
        LGDottedLineView *lineView = [[LGDottedLineView alloc]initWithFrame:CGRectMake(0, lineHeight*i, self.itemWidth*30+viewPix(20), lineHeight)];
        [self.scrollView addSubview:lineView];
    }
    self.y_AxisArray = [NSArray arrayWithArray:labelArray];
    [self addSubview:self.emptyLabel];
}

-(void)createItemView:(NSString *)type{
    NSArray *itemArray = @[];
    if ([type isEqualToString:@"breath"]) {
        //呼吸
        itemArray = @[@"呼吸次数",@"训练时长",@"压力",@"功率",@"能量"];
        
    }else{
        //排痰
        itemArray = @[@"呼吸次数",@"训练时长",@"压力",@"振幅",@"呼气时间"];
    }
    
    CGFloat itemW = (Screen_W-viewPix(50) - viewPix(24))/4.0;
    CGFloat itemH = viewPix(26);
    for (NSInteger i=0; i<itemArray.count; i++) {
        UIButton *itemButton = [UIButton buttonWithBackColor:@"#EFEFEF" cornerRadius:viewPix(13) title:itemArray[i] titleFont:LGFontWeight(12, UIFontWeightMedium) textColor:@"#999999" frame:CGRectMake(viewPix(8)+(itemW+viewPix(8))*(i%4), viewPix(45)+(itemH+viewPix(8))*(i/4), itemW, itemH)];
        [itemButton setSelectTextColor:@"#2E9AFC" backColor:@"#EAF4FF"];
        itemButton.tag = 1000+i;
        [itemButton addTarget:self action:@selector(itemButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:itemButton];
        [self.itemArray addObject:itemButton];
    }
}

-(NSMutableArray *)x_AxisArray{
    if(!_x_AxisArray){
        _x_AxisArray = [NSMutableArray array];
    }
    return _x_AxisArray;
}

-(NSMutableArray *)itemArray{
    if(!_itemArray){
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}

-(NSMutableArray *)btnArray{
    if(!_btnArray){
        _btnArray = [NSMutableArray array];
    }
    return _btnArray;
}

-(NSMutableArray *)lineArray{
    if(!_lineArray){
        _lineArray = [NSMutableArray array];
    }
    return _lineArray;
}

-(UIImageView *)iconView{
    if(!_iconView){
        _iconView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"患者档案-呼吸训练记录"]];
        _iconView.frame = CGRectMake(viewPix(12), viewPix(14), 24, 24);
    }
    return _iconView;
}

-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel lableWithText:@"变化趋势" colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        _titleLabel.frame = CGRectMake(viewPix(40), viewPix(14), viewPix(150), 24);
    }
    return _titleLabel;
}

-(UILabel *)emptyLabel{
    if(!_emptyLabel){
        _emptyLabel = [UILabel lableWithText:@"暂无数据" colorString:@"#666666" textFont:LGFont(15) textAlignment:NSTextAlignmentCenter lines:1];
        _emptyLabel.frame = CGRectMake(0, topMargin-10, Screen_W-viewPix(32), self.bounds.size.height-topMargin);\
        _emptyLabel.backgroundColor = [UIColor whiteColor];
    }
    return _emptyLabel;
}

-(UILabel *)unitLabel{
    if(!_unitLabel){
        _unitLabel = [UILabel lableWithText:@"mg" colorString:@"#666666" textFont:LGFont(12) textAlignment:NSTextAlignmentLeft lines:1];
        _unitLabel.frame = CGRectMake(viewPix(12), topMargin-10, 80, viewPix(17));
    }
    return _unitLabel;
}

-(LGScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[LGScrollView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, scrollWidth, scrollHeight)];
        _scrollView.contentSize = CGSizeMake(self.itemWidth*30+viewPix(20), scrollHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
    }
    return _scrollView;
}

-(LGChartDetailAlertView *)alertView{
    if(!_alertView){
        _alertView = [[LGChartDetailAlertView alloc] initWithFrame:CGRectMake(0, 0, viewPix(140), viewPix(50))];
        _alertView.hidden = YES;
    }
    return _alertView;
}

@end
